<template>
  <div :class="{ 'hidden': hidden }" class="pagination-container">
    <el-pagination :background="background" :current-page.sync="currentPage" :page-size.sync="limit" :layout="layout"
      :page-sizes="pageSizes" :pager-count="pagerCount" :total="total" v-bind="$attrs" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const defProps = withDefaults(defineProps<{
  total: number,
  page: number,
  limit: number,
  pageSizes: number[],
  pagerCount: number,
  layout: string,
  background: boolean,
  hidden: boolean,
}>(), {
  total: 0,
  page: 1,
  limit: 20,
  pageSizes: () => [10, 20, 50, 100],
  pagerCount: document.body.clientWidth < 992 ? 5 : 7,
  layout: 'total, sizes, prev, pager, next, jumper',
  background: true,
  hidden: false,
})

const emits = defineEmits<{
  (e: "pagination", data: { pageNo: number, pageSize: number }): void,
  (e: "update:page", page: number): void,
  (e: "update:limit", limit: number): void,
}>()


const currentPage = computed({
  get() {
    return defProps.page
  },
  set(newValue) {
    emits("update:page", newValue)
  }
});


const handleSizeChange = (val) => {
  if (currentPage.value * val > defProps.total) {
    currentPage.value = 1
  }
  emits("update:limit", val)
  emits('pagination', { pageNo: currentPage.value, pageSize: val })
}

const handleCurrentChange = (val) => {
  emits("update:page", val)
  emits('pagination', { pageNo: val, pageSize: defProps.limit })
}

</script>

<style scoped>
.pagination-container {
  padding: 20px 16px;
}

.pagination-container.hidden {
  display: none;
}
</style>
